﻿using System.Net.Http;
using System.Text;
using System.Text.Json;
using WPFServices.Models;

namespace WPFServices.Services
{
    /// <summary>
    /// 类似axios的HTTP客户端封装
    /// </summary>
    public class ApiClient
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;

        public ApiClient(string baseUrl = "http://localhost:5264/api/")
        {
            _baseUrl = baseUrl.TrimEnd('/') + "/";
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(_baseUrl);
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
        }

        /// <summary>
        /// GET请求 - 获取数据
        /// </summary>
        /// <param name="url">相对路径，如: "Process/GetProcess"</param>
        public async Task<ApiResult<T>> GetAsync<T>(string url)
        {
            try
            {
                var response = await _httpClient.GetAsync(url);
                return await HandleResponse<ApiResult<T>>(response);
            }
            catch (Exception ex)
            {
                return new ApiResult<T>(false, ResultCode.Fail, $"GET请求失败: {ex.Message}", default(T));
            }
        }

        /// <summary>
        /// POST请求 - 创建数据
        /// </summary>
        /// <param name="url">相对路径，如: "Process/CreateProcess"</param>
        /// <param name="data">要发送的数据</param>
        public async Task<ApiResult<T>> PostAsync<T>(string url, object data = null)
        {
            try
            {
                var content = CreateJsonContent(data);
                var response = await _httpClient.PostAsync(url, content);
                return await HandleResponse<ApiResult<T>>(response);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"POST请求异常: {ex.Message}");
                return new ApiResult<T>(false, ResultCode.Fail, $"POST请求失败: {ex.Message}", default(T));
            }
        }

        /// <summary>
        /// PUT请求 - 更新数据
        /// </summary>
        /// <param name="url">相对路径，如: "Process/UpdateProcess/1"</param>
        /// <param name="data">要发送的数据</param>
        public async Task<ApiResult<T>> PutAsync<T>(string url, object data = null)
        {
            try
            {
                var content = CreateJsonContent(data);
                var response = await _httpClient.PutAsync(url, content);
                return await HandleResponse<ApiResult<T>>(response);
            }
            catch (Exception ex)
            {
                return new ApiResult<T>(false, ResultCode.Fail, $"PUT请求失败: {ex.Message}", default(T));
            }
        }

        /// <summary>
        /// DELETE请求 - 删除数据
        /// </summary>
        /// <param name="url">相对路径，如: "Process/DeleteProcess/1"</param>
        public async Task<ApiResult> DeleteAsync(string url)
        {
            try
            {
                var response = await _httpClient.DeleteAsync(url);
                return await HandleResponse<ApiResult>(response);
            }
            catch (Exception ex)
            {
                return new ApiResult(false, ResultCode.Fail, $"DELETE请求失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建JSON内容
        /// </summary>
        private StringContent CreateJsonContent(object data)
        {
            if (data == null)
                return new StringContent("", Encoding.UTF8, "application/json");

            string jsonString = JsonSerializer.Serialize(data, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            return new StringContent(jsonString, Encoding.UTF8, "application/json");
        }

        /// <summary>
        /// 处理响应结果
        /// </summary>
        private async Task<T> HandleResponse<T>(HttpResponseMessage response)
        {
            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                if (string.IsNullOrEmpty(responseContent))
                    return default(T);

                return JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            else
            {
                
                // 如果是ApiResult类型，返回失败结果
                if (typeof(T) == typeof(ApiResult))
                {
                    return (T)(object)new ApiResult(false, ResultCode.Fail, $"请求失败 - 状态码: {response.StatusCode}, 错误信息: {responseContent}");
                }
                else if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(ApiResult<>))
                {
                    var dataType = typeof(T).GetGenericArguments()[0];
                    var failResult = Activator.CreateInstance(typeof(ApiResult<>).MakeGenericType(dataType),
                        false, ResultCode.Fail, $"请求失败 - 状态码: {response.StatusCode}, 错误信息: {responseContent}", null);
                    return (T)failResult;
                }

                throw new Exception($"请求失败 - 状态码: {response.StatusCode}, 错误信息: {responseContent}");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}